package com.menusifu.cloudmenu.dao.impl;

import com.menusifu.cloudmenu.dao.CategoryDao;
import com.menusifu.cloudmenu.entity.Category;
import com.menusifu.cloudmenu.entity.SaleItem;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * @author xie
 * @date 2019/1/15 14:36
 * @description:
 */
@Repository
public class CategoryDaoImpl implements CategoryDao {
    @Autowired
    MongoTemplate mongoTemplate;

    @Override
    public List<Category> getAllCategories() {
        Query query = new Query(Criteria.where("deleted").is(Boolean.FALSE));
        return mongoTemplate.find(query, Category.class);
    }

    @Override
    public void addCategory(Category category) {
        mongoTemplate.insert(category, "Category");
    }

    @Override
    public void updateCategory(Category category) {
        // need to think the data structure
        Query query = new Query(Criteria.where("id").is(category.getId()).and("deleted").is(Boolean.FALSE));
        Update update = Update.update("categoryName", category.getCategoryName())
                .set("description", category.getDescription())
                .set("lastUpdatedBy", category.getLastUpdatedBy())
                .set("lastUpdated", category.getLastUpdated())
                .set("taxId", category.getTaxId());
        mongoTemplate.findAndModify(query, update, Category.class);
    }

    @Override
    public void deleteCategory(String id) {
        Query query = new Query(Criteria.where("id").is(id).and("deleted").is(Boolean.FALSE));
        Update update = Update.update("deleted", Boolean.TRUE);
        mongoTemplate.findAndModify(query, update, Category.class);
    }

    @Override
    public Category getCategoryById(String id) {
        Query query = new Query(Criteria.where("id").is(id).and("deleted").is(Boolean.FALSE));
        return mongoTemplate.findOne(query, Category.class);
    }
}
